/**
 * 
 */
package com.pkdl.tables;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.TableColumnModel;

/**
 * @author Administrator
 * 
 */
public class TableButtonMouseListener implements MouseListener {
	private JTable __table;

	public TableButtonMouseListener(JTable table) {
		this.__table = table;
	}

	private void __forwardEventToButton(MouseEvent e) {
		TableColumnModel columnModel = this.__table.getColumnModel();
		int column = columnModel.getColumnIndexAtX(e.getX());
		int row = e.getY() / this.__table.getRowHeight();
		Object value;
		JButton button;
		MouseEvent buttonEvent;
		if (row >= this.__table.getRowCount() || row < 0
				|| column >= this.__table.getColumnCount() || column < 0) {
			return;
		}
		value = this.__table.getValueAt(row, column);
		if (!(value instanceof JButton)) {
			return;
		}
		button = (JButton) value;
		buttonEvent = SwingUtilities.convertMouseEvent(this.__table, e, button);
		button.dispatchEvent(buttonEvent);
		// This is necessary so that when a button is pressed and released
		// it gets rendered properly. Otherwise, the button may still appear
		// pressed down when it has been released.
		this.__table.repaint();
	}

	public void mouseClicked(MouseEvent e) {
	}

	public void mouseEntered(MouseEvent e) {
	}

	public void mouseExited(MouseEvent e) {
	}

	public void mousePressed(MouseEvent e) {
		this.__forwardEventToButton(e);
	}

	public void mouseReleased(MouseEvent e) {
	}
}
